soda()
	._module(['sdAutocomplete', 'dtree'])
	._page('iam_appliction')
	._api('/v1/iam/app')
	._query(['name^like^', 'state^eq^-1'])
	._orderBy(['createTime^desc'])
	._run((unit) => {
		let appId = '';
		// api配置
		unit.api['permission'] = '/v1/iam/app/permission';
		unit.api['permissionReload'] = '/v1/iam/app/permission/reload';
		unit.api['administratorCrud'] = '/v1/iam/user/application';
		unit.api['administrator'] = '/v1/iam/user/application/list';
		unit.api['autocomplete'] = '/v1/iam/user/list?where=mobile:like:';
		unit.api['role'] = '/v1/iam/role/platform';
		unit.api['role-permission'] = '/v1/iam/role/permission';
		unit.api['role-curd'] = '/v1/iam/role';
		// id配置
		unit.el['tableAdministrator'] = unit.key + '_administrator_table';

		// 表单配置
		unit.templateForm['verify'] = ["name", "code"];
		unit.templateForm['items'] = [
			{code: 1, name:'name', title:'应用名称', placeholder:'请输入应用名称', attr: 'maxlength=20'},
			{code: 1, name:'code', title:'应用编码', placeholder:'请输入应用编码', attr: 'maxlength=20'},
			{code: 1, name:'panel', title:'首页面板', placeholder:'请输入面板路由地址', attr: 'maxlength=50'},
			{code: 1, name:'icon', title:'应用图标', placeholder:'图标URL地址', attr: 'maxlength=100'},
			{code: 2, name:'state', title:'状态', options: unit.globalConstant['enableState']},
			{code: 5, type:'text', name:'remark', title:'备注', placeholder:'备注信息'}
		];
		unit['role-form'] = {};
		unit['role-form']['id'] = 'iam_application_role_form';
		unit['role-form']['verify'] = ["name"];
		unit['role-form']['items'] = [
			{code: 1, name:'name', title:'角色名称', placeholder:'请输入角色名称', attr: 'maxlength=20'},
			{code: 1, name:'grade', title:'等级', type: 'number',attr: 'max=5 ', placeholder:'角色等级 1-5数字越小优先级越大', },
			{code: 2, name:'isDefault', title:'默认角色', options: unit.globalConstant['dataDefault']},
			{code: 2, name:'state', title:'状态', options: unit.globalConstant['enableState']},
			{code: 5, type:'text', name:'remark', title:'备注', placeholder:'备注信息'}
		];
		
		// 表格基础配置
		unit.templateTable['cols'] = [
			{fixed: 'left', field: 'name', title: '应用名称', minWidth: 120},
			{fixed: 'left', field: 'code', title: '编码', minWidth: 120},
			{field: 'panel', title: '面板页'},
			{field: 'icon', title: '图标'},
			{field: 'state', title: '状态',templet(obj) {
			    return unit.sdFormat['json']['get'](unit.globalConstant['enableState'], obj.state, 'value').title;
			}},
			{field: 'createTime', title: '创建时间'},
			{field: 'updateTime', title: '上次修改', templet(obj) {
			    let ct = obj.createTime;
			    let ut = obj.updateTime;
			    return ct == ut ? '' : ut;
			}},
			{fixed: 'right', title: '操作', minWidth: 320, toolbar: unit.sysApplication['btns']['right']()},
		];
		unit.templateTable['bar'] = (bar) => {
			unit.templateDialog[bar.event]();
		}
		unit.templateTable['tool'] = (tool) => {
			unit.templateDialog[tool.event](tool.data);
		}
		unit.templateTable['info'] = {
			height: '420px',
			data: [
			    {field: 'name', title: '应用名称'},
			    {field: 'code', title: '应用名称'},
			    {field: 'panel', title: '面板页'},
			    {field: 'icon', title: '图标'},
			    {field: 'state', title: '状态',templet: function (obj) {
			        return unit.sdFormat['json']['get'](unit.globalConstant['enableState'], obj, 'value').title;
			    }},
			    {field: 'accessKey', title: '密钥'},
			    {field: 'accessSecret', title: '密匙'},
			    {field: 'createTime', title: '创建时间'}
			]
		}
		// 表格查询配置
		unit.templateTable['search']['components'] = [
			{code:1, name:"name", title:"应用名称", placeholder:"请输入要查询的关键字"},
			{code:3, name:"state", title:"状态", options: unit.globalConstant['enableState']}
		]
		unit.templateTable['search']['submit'] = (data) => {
			unit.sdTable.reload(unit.el['table'], {
				where: unit.sdFormat['query'](unit.filter['vo'], data)
			});
		}
		
		// 渲染
		unit.render['autocomplete'] = (data) => {
			unit.sdAutocomplete.render({
			    id: "user-key",
			    cols: [
					{field: 'realName',title: '姓名'},
			        {field: 'mobile',title: '电话'},
				], 
			    type: 'sugTable', //设置输入框提示类型：sug-下拉框，sugTable-下拉表格
			    url: unit.api['autocomplete'],
			    callback(d){
			        let form = {
			            userId: d.id,
			            appId: data.id
			        }
			        let param = {
			            url: unit.api['administratorCrud'],
			            data: form,
			            tips: true,
			            callback: function (d) {
			                unit.sdTable['reload'](unit.el['tableAdministrator']);
			            }
			        }
			        unit.sdHttp['post'](param);
			    }
			})
		}
		
		// 弹出层
		unit.templateDialog['form'] = (data) => {
			unit.sdDialog.form({
			    title: data ? '修改' : "创建",
			    height: '560px',
			    init: function (){
			        unit.sdForm['init']['form'](unit.templateForm, data);
			    },
			    opt: function (index) {
			        // 获取form
			        let form = unit.sdForm['get'](unit.el['form'], unit.templateForm['verify']);
			        // 校验数据
			        if(!form.check){
						unit.sdDialog['tips']['warning'](form.message);
			            return false;
			        }
			        let val = form.data;
			        val['state'] = val['state'] || 1;
			       
			        let param = {
						url: unit.api['crud'],
			            data: val,
			            tips: true,
			            callback: function () {
							unit.sdDialog['close'](index);
							unit.sdTable['reload'](unit.el.table);
			            }
			        }
			        // 操作
					data ? unit.sdHttp['put'](param, data.id) : unit.sdHttp['post'](param);
			    }
			})
		}
		unit.templateDialog['create'] = unit.templateDialog['form'];
		unit.templateDialog['update'] = unit.templateDialog['form'];
		unit.templateDialog['delete'] = (data) => {
			unit.sdDialog.confirm({
				title: "是否要删除这条数据?",
				submit() {
					let param = {
						url: unit.api['crud'],
						callback() {
							unit.sdTable['reload'](unit.el.table)
						}
					}
					unit.sdHttp['delete'](param, data.id);
				}
			});
		}
		unit.templateDialog['reloadPermission'] = (data) => {
			unit.sdDialog.confirm({
			    title: "是否要对改子系统进行权限重载?",
			    submit: function () {
			        let param = {
			            url: unit.api['permissionReload'],
			            tips: true
			        }
					unit.sdHttp['get'](param, data.id);
			    }
			});
		}
		unit.templateDialog['removeAuth'] = (data) => {
			unit.sdDialog.confirm({
			    title: "是否要移除该管理员权限?",
			    submit: function () {
			        let param = {
			            url: unit.api['administratorCrud'] + "/admin",
			            callback: function () {
			                unit.sdTable['reload'](unit.el['tableAdministrator']);
			            }
			        }
			        unit.sdHttp['delete'](param, data.id);
			    }
			});
		}
		unit.templateDialog['administrator'] = (data) => {
			unit.sdDialog.page({
			    title: "应用管理员",
			    height: '450px',
			    url: '/components/iam/application/administrator.html',
			    btn: [],
			    init: function (){
			        unit.render['autocomplete'](data);
			        let aConfig = {
			            id: unit.el['tableAdministrator'],
			            url: unit.api['administrator'],
			            toolbar: false,
			            limit: 6,
			            height: '300px',
			            where: {
			                where: 'isAdmin:eq:1~appId:eq:' + data.id
			            },
			            cols: [
			                {fixed: 'left', field: 'realName', title: '姓名', minWidth: 120,templet(obj){
			                    return obj.user.realName;
			                }},
			                {fixed: 'left', field: 'mobile', title: '手机号', minWidth: 120, templet(obj){
			                    return obj.user.mobile;
			                }},
			                {field: 'createTime', title: '登记时间', minWidth: 120},
			                {fixed: 'right', title: '操作', minWidth: 120, 
			                    toolbar: '<div class="layui-table-cell">'+
			                                '<a class="layui-btn layui-btn-xs" lay-event="removeAuth">降权</a>' +
			                             '</div>'},
			            ],
			            tool: function (row) {
							unit.templateDialog[row.event](row.data);
			            },
			        }
			        unit.sdTable['render'](aConfig);
			    }
			})
		}
		unit.templateDialog['permission'] = (data) => {
			unit.sdDialog.page({
                title: "权限配置",
                url: '/components/iam/application/permission.html',
                init: function (){
                    let param = {
                        url: unit.api['permission'],
                        callback: function (d) {
                            unit.dtree['render']({
                                elem: '#app-auth-tree',
                                data: d,
                                type: "all",
                                checkbar:true,
                                initLevel: 3,
                                checkbarType: "all",
                                checkbarData: "choose",
                                dot: false,
                                skin: "zdy"
                            });
                        }
                    }
                    unit.sdHttp['get'](param, data.id);
                },
                opt: function (index) {
                    let auths = unit.dtree['getCheckbarNodesParam']("app-auth-tree");
                    let param = {
                        url: unit.api['permission'],
                        data: auths,
                        tips: true,
                        callback: function (d) {
                            unit.sdDialog['close'](index);
                        }
                    }
                    unit.sdHttp['put'](param, data.id);
                }
            })
		}
		unit.templateDialog['role'] = (data) => {
			appId = data.id;
			console.log('appId', appId)
			unit.sdDialog.page({
				title: "角色配置",
				btn: [],
				height: '660px',
				width: '800px',
				url: '/components/iam/application/role.html',
				init: function (){
					// 角色表格
					unit['roleTable'] = {};
					unit['roleTable']['height'] = "540px";
					unit['roleTable']['id'] = 'iam_appliction_role_table';
					unit['roleTable']['url'] = unit.api['role'] + '/list?where=appId:eq:' + data.id;
					unit['roleTable']['toolbar'] = '<div class="layui-table-tool-temp"><button class="layui-btn layui-btn-sm" lay-event="create-role">创建角色</button></div>'
					unit['roleTable']['cols'] = [
						{fixed: 'left', field: 'name', title: '角色名称', minWidth: 120},
						{field: 'grade', title: '等级'},
						{field: 'isDefault', title: '默认',templet(obj) {
						    return unit.sdFormat['json']['get'](unit.globalConstant['dataDefault'], obj.isDefault, 'value').title;
						}},
						{field: 'state', title: '状态',templet(obj) {
						    return unit.sdFormat['json']['get'](unit.globalConstant['enableState'], obj.state, 'value').title;
						}},
						{field: 'createTime', title: '创建时间'},
						{field: 'updateTime', title: '上次修改', templet(obj) {
						    let ct = obj.createTime;
						    let ut = obj.updateTime;
						    return ct == ut ? '' : ut;
						}},
						{fixed: 'right', title: '操作', minWidth: 180, toolbar: '<div class="layui-table-cell laytable-cell-2-0-6"><a  class="layui-btn layui-btn-xs" lay-event="permission-role">权限</a><a class="layui-btn layui-btn-xs" lay-event="update-role">编辑</a><a  class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete-role">删除</a></div>'},
					];
					unit['roleTable']['bar'] = (bar) => {
						unit.templateDialog[bar.event]();
					}
					unit['roleTable']['tool'] = (tool) => {
						unit.templateDialog[tool.event](tool.data);
					}
					unit.sdTable['render'](unit['roleTable']);
				},
				opt: function (index) {
					
				}
			})
		}
		
		unit.templateDialog['role-form'] = (data) => {
			unit.sdDialog.form({
				title: data ? '修改' : "创建",
				height: '500px',
				init() {
					unit.sdForm['init']['form'](unit['role-form'], data);
				},
				opt(index) {
					// 获取form
					let form = unit.sdForm['get'](unit['role-form']['id'], unit['role-form']['verify']);
					
					// 校验数据
					if (!form.check) {
						unit.sdDialog['tips']['warning'](form.message);
						return false;
					}
					
					// 数据处理
					let val = form.data;
					val['state'] = val['state'] || 1;
					val['grade'] = val['grade'] || 3;
					val['appId'] = appId;
					let param = {
						url: unit.api['role-curd'],
						data: val,
						tips: true,
						callback() {
							unit.sdDialog['close'](index);
							unit.sdTable['reload']('iam_appliction_role_table');
						}
					}
					// 操作
					data ? unit.sdHttp['put'](param, data.id) : unit.sdHttp['post'](param);
				}
			})
		}
		unit.templateDialog['create-role'] = unit.templateDialog['role-form'];
		unit.templateDialog['update-role'] = unit.templateDialog['role-form'];
		unit.templateDialog['delete-role'] = (data) => {
			unit.sdDialog.confirm({
				title: "是否要删除这条数据?",
				submit() {
					let param = {
						url: unit.api['role-curd'],
						callback() {
							unit.sdTable['reload']('iam_appliction_role_table')
						}
					}
					unit.sdHttp['delete'](param, data.id);
				}
			});
		}
		unit.templateDialog['permission-role'] = (data) => {
			unit.sdDialog.page({
				title: "权限配置",
				url: '/components/iam/application/permission.html',
				init: function (){
				    let param = {
				        url: unit.api['role-permission'],
				        callback: function (d) {
				            unit.dtree.render({
				                elem: '#app-auth-tree',
				                data: d,
				                type: "all",
				                checkbar:true,
				                initLevel: 3,
				                checkbarType: "all",
				                checkbarData: "choose",
				                dot: false,
				                skin: "zdy"
				            });
				        }
				    }
				   unit.sdHttp['get'](param, data.id);
				},
				opt: function (index) {
				    let auths = unit.dtree.getCheckbarNodesParam("app-auth-tree");
				    let param = {
				        url: unit.api['role-permission'],
				        data: auths,
				        tips: true,
				        callback: function (d) {
							unit.sdDialog['close'](index);
				        }
				    }
				    unit.sdHttp['put'](param, data.id);
				}
			});
		}
		
		// 渲染表格
		unit.sdTable['render'](unit.templateTable);
	})
